

library(tidyverse)
library(rio)
library(countrycode)
library(wesanderson)

setwd("~/04_de_soysa_neumayer_2005")

full_data <- import("replication_data.dta")


world <- map_data("world") %>%
  filter(region != "Antarctica") %>%
  mutate(wdicode = countrycode(region, 'country.name', 'wb', warn = T))


data_og <- full_data %>%
  select(wdicode,year,gsrgnicorrected,Llntrd,Llngni,Llngni2,Lgrowth,Laggdp,
         Lcurrencycrisis,expoil,Ldemoc2,Lpolcon3,Lstabs,Llnden,Llnpop,Llnurban,
         Lbigwar,peaceyrs46)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "Original Data")

data_2002 <- full_data %>%
  select(wdicode,year,gsrgnicorrected_2002,Llntrd_2002,Llngni_2002,Llngni2_2002,
         Lgrowth_2002,Laggdp_2002,Lcurrencycrisis,expoil,Ldemoc2,Lpolcon3,Lstabs,
         Llnden_2002,Llnpop_2002,Llnurban_2002,Lbigwar,peaceyrs46)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2002")

data_2012 <- full_data %>%
  select(wdicode,year,gsrgnicorrected_2012,Llntrd_2012,Llngni_2012,Llngni2_2012,
         Lgrowth_2012,Laggdp_2012,Lcurrencycrisis,expoil,Ldemoc2,Lpolcon3,Lstabs,
         Llnden_2012,Llnpop_2012,Llnurban_2012,Lbigwar,peaceyrs46)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2012")

data_2022 <- full_data %>%
  select(wdicode,year,gsrgnicorrected_2022,Llntrd_2022,Llngni_2022,Llngni2_2022,
         Lgrowth_2022,Laggdp_2022,Lcurrencycrisis,expoil,Ldemoc2,Lpolcon3,Lstabs,
         Llnden_2022,Llnpop_2022,Llnurban_2022,Lbigwar,peaceyrs46)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2022")

map_data <- rbind(data_og,data_2002,data_2012,data_2022)

pal <- wes_palette("Zissou1", 100, type = "continuous")
map_data %>%
  ggplot(aes(long, lat, group = group)) + 
  geom_polygon(aes(fill = n), color = "gray92", linewidth = 0.001) + facet_wrap (~ name) + 
  theme_void() + labs(fill="Number of \nAvailable \nObservations") +
  scale_fill_gradientn(colours = pal, na.value="gray92") + 
  theme(plot.margin = unit(c(0,0,0,0), "cm")) +
  theme(strip.text.x = element_text(size = 12, face = "bold", hjust = 0.5))

# ggsave(filename = "map_available_desoysa.pdf", height = 7, width = 12)
